package com.tuanzi.loan.business.service.collaborate.impl;

import com.base.common.log.LogService;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.gson.JsonObject;
import com.starbaba.model.utils.JSONUtils;
import com.tuanzi.loan.business.entity.collaborate.NewCollaborateChannelRatio;
import com.tuanzi.loan.business.entity.common.CommProductChannel;
import com.tuanzi.loan.business.repository.collaborate.CollaborateChannelRatioRepository;
import com.tuanzi.loan.business.service.collaborate.CollaborateChannelRatioService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.core.service.CommonServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.retry.RetryException;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDate;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * User: liangZongXi
 * Create time: 16:36 2018/9/18
 * Description:
 */
@Debug
@Service
@Transactional
@Retryable(value = { RetryException.class })
public class CollaborateChannelRatioServiceImpl extends CommonServiceImpl<NewCollaborateChannelRatio,Integer> implements CollaborateChannelRatioService{

    @Autowired
    private CollaborateChannelRatioRepository collaborateChannelRatioRepository;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Value("${loan.common.activity.url}")
    private String commonActivityUrl;


    @Override
    protected JpaRepository<NewCollaborateChannelRatio, Integer> getRepository() {
        return collaborateChannelRatioRepository;
    }

    @Override
    public Boolean updateCollaborateData() {

        if(StringUtils.isBlank(commonActivityUrl)){
            LogService.info("刷新通用活动统计(按产品ID)失败，无法从配置文件获取url");
            return false;
        }

        String url = String.format(commonActivityUrl, LocalDate.now().toString());

        //统计当天数据
        RestTemplate restTemplate = new RestTemplate();
        String forObject = restTemplate.getForObject(url, String.class, Maps.newHashMap());
        LogService.info("刷新统计通用活动统计(按产品ID)结果： " + forObject);

        JsonObject resultJson = JSONUtils.toJsonObject(forObject);
        int status = resultJson.get("result").getAsJsonObject().get("status").getAsInt();

        return 1 == status;
    }

    @Override
    public Set<Integer> findCurrentUserShowType(List<CommProductChannel> currentUserChannelList) {
        HashSet<Integer> typeSet = Sets.newHashSet();

        if(currentUserChannelList == null || currentUserChannelList.size() <= 0){
            return typeSet;
        }
        List<Integer> channelList = currentUserChannelList.stream().map(CommProductChannel::getChannelCode).collect(Collectors.toList());
        List<NewCollaborateChannelRatio> channelRatios = collaborateChannelRatioRepository.findByChannelIdIn(channelList);
        if(channelRatios == null || channelRatios.size() <=0){
            return typeSet;
        }

        channelRatios.forEach(a -> {
            typeSet.add(a.getShowType());
        });

        return typeSet;
    }

    @Override
    public Set<Integer> findCurrentUserMarketShow(List<CommProductChannel> currentUserChannelList) {
        HashSet<Integer> typeSet = Sets.newHashSet();

        if(currentUserChannelList == null || currentUserChannelList.size() <= 0){
            return typeSet;
        }
        List<Integer> channelList = currentUserChannelList.stream().map(CommProductChannel::getChannelCode).collect(Collectors.toList());
        List<NewCollaborateChannelRatio> channelRatios = collaborateChannelRatioRepository.findByChannelIdIn(channelList);
        if(channelRatios == null || channelRatios.size() <=0){
            return typeSet;
        }

        channelRatios.forEach(c ->{
            String marketShow = c.getMarketShow();
            if(StringUtils.isNotBlank(marketShow)){
                String[] split = marketShow.split(",");
                for (String show : split) {
                    typeSet.add(Integer.valueOf(show));
                }
            }
        });

        return typeSet;
    }

    @Override
    public Set<Integer> findCurrentUserCheckInShow(List<CommProductChannel> currentUserChannelList) {
        HashSet<Integer> typeSet = Sets.newHashSet();

        if(currentUserChannelList == null || currentUserChannelList.size() <= 0){
            return typeSet;
        }
        List<Integer> channelList = currentUserChannelList.stream().map(CommProductChannel::getChannelCode).collect(Collectors.toList());
        List<NewCollaborateChannelRatio> channelRatios = collaborateChannelRatioRepository.findByChannelIdIn(channelList);
        if(channelRatios == null || channelRatios.size() <=0){
            return typeSet;
        }

        channelRatios.forEach(c ->{
            String checkShow = c.getCheckShow();
            if(StringUtils.isNotBlank(checkShow)){
                String[] split = checkShow.split(",");
                for (String show : split) {
                    typeSet.add(Integer.valueOf(show));
                }
            }
        });

        return typeSet;
    }

    @Override
    public NewCollaborateChannelRatio findCollaborateChannelRatioByChannelId(Integer channelId) {
        return collaborateChannelRatioRepository.findCollaborateChannelRatioByChannelId(channelId);
    }

    @Override
    public void updateRatioFromTomorrowRatio() {
        collaborateChannelRatioRepository.updateRatioFromTomorrowRatio();
    }
}
